import './index.css'
import {Button, Form, Input, message, Modal, Popconfirm, Select, Switch, Table} from "antd"
import {useCallback, useEffect, useState} from "react"
import {useOutletContext} from "react-router-dom"
import {DatabaseOutlined, SearchOutlined} from "@ant-design/icons"
import {changeUser, createUser, deleteUser, getAllUser, queryUser, setUserEnable} from "../../../request/user"
import {getAllRole} from "../../../request/role"

const columns = [
    {
        title: '账号',
        dataIndex: 'uid',
        key: 'uid',
        align: 'center',
        width: 150
    },
    {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        width: 150
    },
    {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
        align: 'center',
        width: 150
    },
    {
        title: '角色',
        dataIndex: 'roleName',
        key: 'roleName',
        align: 'center',
        width: 150
    },
    {
        title: '添加时间',
        dataIndex: 'created_at',
        key: 'created_at',
        align: 'center',
        width: 200
    },
    {
        title: '最后登录',
        dataIndex: 'last_login_at',
        key: 'last_login_at',
        align: 'center',
        width: 200
    },
    {
        title: '是否启用',
        dataIndex: 'enable',
        key: 'enable',
        align: 'center',
        width: 100
    },
    {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        align: 'center'
    }
]

function User() {
    const [onMenuChange] = useOutletContext()
    let [data, setData] = useState([])
    let [editing, setEditing] = useState({})
    let [title, setTitle] = useState('')
    let [search, setSearch] = useState('')
    let [roleOptions, setRoleOptions] = useState([])
    let [roleMap, setRoleMap] = useState({})
    const [form] = Form.useForm()

    useEffect(() => {
        getAllRole().then(roles => {
            setRoleOptions(roles.map(role => ({
                key: role.id,
                value: role.id,
                label: role.name
            })))
            const roleMap = {}
            for (const role of roles) {
                roleMap[role.id] = role.name
            }
            setRoleMap(roleMap)
        })
    }, [])

    const loadUsers = useCallback((uidOrName = undefined) => {
        function enableUser(user, enable) {
            setUserEnable(user.uid, enable).then(() => {
                onMenuChange()
            }).catch(message.error)
        }

        function doDeleteUser(user) {
            deleteUser(user.uid).then(() => {
                onMenuChange()
                loadUsers()
                message.success('删除成功')
            }).catch(message.error)
        }

        function loadUsersInner(data) {
            return data.map(user => {
                delete user.password
                user.key = user.uid
                user.roleName = roleMap[user.role]
                user.enable = <Switch defaultChecked={user.enable} onChange={
                    (checked) => enableUser(user, checked)
                }/>
                user.operation = (
                    <>
                        <Button type="link" onClick={() => {
                            setTitle('编辑用户')
                            setEditing(user)
                            form.setFieldsValue(user)
                        }}>编辑</Button>
                        <Popconfirm
                            title="确认删除"
                            description="你确定要删除该用户吗?"
                            onConfirm={() => {
                                doDeleteUser(user)
                            }}
                            okText="是"
                            cancelText="否"
                        >
                            <Button type="link">删除</Button>
                        </Popconfirm>
                    </>
                )
                return user
            })
        }

        if (uidOrName) {
            queryUser(uidOrName).then(users => {
                setData(loadUsersInner(users))
                message.success(`查询到${users.length}个用户`)
            }).catch(message.error)
        } else {
            getAllUser().then(users => {
                setData(loadUsersInner(users))
            }).catch(message.error)
        }
    }, [form, onMenuChange, roleMap])
    useEffect(loadUsers, [loadUsers])

    function tryEdit(args) {
        const promise = editing.key !== -1 ?
            changeUser(editing.id, args) : createUser(args)
        promise.then(() => {
            setEditing({})
            onMenuChange()
            loadUsers()
            message.success(editing.key !== -1 ? '修改成功' : '创建成功')
        }).catch(message.error)
    }

    return (
        <>
            <div className="content-item-box">
                <div className="search">
                    <div className="label"><SearchOutlined/>筛选搜索</div>
                    <label>
                        <span>输入搜索</span>
                        <Input placeholder="请输入账号/姓名" value={search}
                               onChange={e => setSearch(e.target.value)}></Input>
                    </label>
                </div>
                <div className="blank"></div>
                <Button onClick={() => {
                    setSearch('')
                    loadUsers()
                }}>重置</Button>
                <Button type="primary" onClick={() => {
                    loadUsers(search)
                }}>搜索</Button>
            </div>
            <div className="content-item-box">
                <DatabaseOutlined/>
                <span>数据列表</span>
                <div className="blank"></div>
                <Button onClick={() => {
                    setTitle('添加用户')
                    const editing = {
                        key: -1,
                        uid: undefined,
                        name: undefined,
                        email: undefined,
                        password: undefined,
                        role: undefined
                    }
                    setEditing(editing)
                    form.setFieldsValue(editing)
                }}>添加</Button>
            </div>
            <Modal
                title={title}
                open={editing.key}
                //onOk={handleOk}
                onCancel={() => setEditing({})}
                footer={[]}
                width={420}
            >
                <Form
                    className="edit-form"
                    labelCol={{span: 4}}
                    onFinish={tryEdit}
                    form={form}>
                    <Form.Item
                        name="uid"
                        label="账号"
                        rules={[
                            {
                                required: true,
                                message: '请输入账号',
                            },
                        ]}
                    >
                        <Input placeholder="请输入账号"/>
                    </Form.Item>

                    <Form.Item
                        name="name"
                        label="姓名"
                        rules={[
                            {
                                required: true,
                                message: '请输入姓名',
                            },
                        ]}
                    >
                        <Input placeholder="请输入姓名"/>
                    </Form.Item>

                    <Form.Item
                        name="email"
                        label="邮箱"
                        rules={[
                            {
                                required: true,
                                message: '请输入邮箱',
                            },
                            {
                                pattern: /^\w+@[a-z]+(\.[a-z]+)*$/,
                                message: '请输入正确的邮箱格式'
                            }
                        ]}
                    >
                        <Input placeholder="请输入邮箱"/>
                    </Form.Item>

                    <Form.Item
                        name="role"
                        label="角色"
                        rules={[
                            {
                                required: true,
                                message: '请选择角色',
                            }
                        ]}
                    >
                        <Select options={roleOptions} placeholder='请选择角色'/>
                    </Form.Item>

                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[
                            {
                                required: editing.key === -1,
                                message: '请输入密码'
                            },
                            {
                                pattern: /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
                                message: '密码必须包含大小字母及数字'
                            },
                            {
                                min: 8,
                                max: 16,
                                message: '密码长度必须在8到16位之间'
                            }
                        ]}
                    >
                        <Input placeholder={editing.key === -1 ? "请输入密码" : "请输入新密码【不输入则不更改密码】"}/>
                    </Form.Item>

                    <Form.Item>
                        <Button onClick={() => setEditing({})}>取消</Button>
                        <Button type="primary" htmlType="submit">确定</Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Table
                columns={columns}
                dataSource={data}
                pagination={false}
            />
        </>
    )
}

export default User